package com.dek.grpc.helloworld;

import com.dek.grpc.dto.HelloReply;
import com.dek.grpc.dto.HelloRequest;
import com.dek.grpc.service.HelloServiceGrpc;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;

import java.io.IOException;
import java.util.logging.Logger;

public class HelloWorldServer {

    private static final Logger LOGGER = Logger.getLogger(HelloWorldServer.class.getName());

    private Server server;

    private void start() throws IOException {
        int port = 5001;
        server = ServerBuilder.forPort(port).addService(new HelloWorldImpl())
                                .build()
                                .start();
        LOGGER.info("Server started, listening on " + port);

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.err.println("*** shutting down gRPC server since JVM is shutting down");
            HelloWorldServer.this.stop();
            System.err.println("*** server shut down");
        }));
    }

    private void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    static class HelloWorldImpl extends HelloServiceGrpc.HelloServiceImplBase {
        @Override
        public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
            System.out.println("greet from " + request.getName());
            HelloReply reply = HelloReply.newBuilder().setMessage("hello" + request.getName()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }


    public static void main(String[] args) throws IOException, InterruptedException {
        final HelloWorldServer server = new HelloWorldServer();
        server.start();

        if (server.server != null) {
            server.server.awaitTermination();
        }
    }


}
